<?php

/**
 * Louder Cache
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file docs/LICENSE.txt.
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@loudertechnology.com so we can send you a copy immediately.
 *
 * @category Louder
 * @package ClusterConfig
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */

/**
 * Configuracion del Cluster
 *
 * @category Louder
 * @package ClusterConfig
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */
class ClusterConfig {

	/**
	 * Crea la configuracion PHP apartir de el descriptor XML
	 *
	 * @param string $configFile
	 */
	public static function createConfig($configFile){
		$document = new DOMDocument();
		if($document->load($configFile)==true){
			$config = array();
			foreach($document->getElementsByTagName("partition") as $partition){
				$i = 0;
				$instanceName = "";
				foreach($partition->getElementsByTagName("instance") as $instance){
					$instanceName = $instance->getAttribute("name");
				}
				$attributes = array();
				foreach($partition->getElementsByTagName("node") as $node){
					$attributes[$i] = array();
					foreach($node->getElementsByTagName("attribute") as $attribute){
						$attributes[$i][$attribute->getAttribute("name")] = $attribute->nodeValue;
					}
					$i++;
				}
				$config[$instanceName] = $attributes;
			}
			$dirName = dirname($configFile);
			if(is_writable($dirName)==true){
				file_put_contents($configFile.".php", "<?php \$config = unserialize('".serialize($config)."');");
			} else {
				throw new ClusterConfigException("El directorio '$dirName' debe tener permisos de escritura");
			}
		} else {
			throw new ClusterConfigException("El archivo '$configFile' contiene una estructura XML invalida");
		}
	}

	/**
	 * Lee el archivo de configuracion cacheado
	 *
	 * @param string $configFile
	 * @return array
	 */
	public static function read($configFile){
		if(file_exists($configFile.".php")){
			require $configFile.".php";
			return $config;
		} else {
			throw new ClusterConfigException("No existe el archivo temporal '$configFile.php'");
		}
	}

}


